﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace SeventhHabit.Dbm.Model {
    public class DbManager {
        #region Readonly & Static Fields

        private readonly IScriptRunner _scriptRunner;

        #endregion

        #region C'tors

        public DbManager(IScriptRunner scriptRunner) {
            _scriptRunner = scriptRunner;
        }

        #endregion

        #region Instance Methods

        public void UpgradeDatabase(string scriptFolder) {
            var scriptFiles = new List<string>();
            scriptFiles.AddRange(Directory.GetFiles(scriptFolder, "*.sql"));
            scriptFiles.AddRange(Directory.GetFiles(scriptFolder, "*.nsql"));

            UpgradeDatabase(scriptFiles.ToArray());
        }

        public void UpgradeDatabase(string[] scriptFilePaths) {
            ValidateScriptFilePaths(scriptFilePaths);
            Array.Sort(scriptFilePaths);
            foreach (string scriptFilePath in scriptFilePaths)
                _scriptRunner.Execute(scriptFilePath);
        }

        #endregion

        #region Class Methods

        private static void Validate(string scriptFilePath) {
            const string regex = @"^\d{3}\.\d{3}\.\d{4}\.*.*\.n*sql$";
            if (!Regex.IsMatch(scriptFilePath, regex)) {
                throw new FormatException(string.Format("Script file name [{0}] does not match required format [{1}]",
                                                        scriptFilePath, regex));
            }
        }

        private static void ValidateScriptFilePaths(string[] scriptFilePaths) {
            foreach (string scriptFilePath in scriptFilePaths)
                Validate(Path.GetFileName(scriptFilePath));
        }

        #endregion
    }
}